package com.example.demo.zjitc.server.service.impl;

import com.example.demo.zjitc.server.mapper.PermissionMapper;
import com.example.demo.zjitc.server.mapper.RoleMapper;
import com.example.demo.zjitc.server.pojo.Permission;
import com.example.demo.zjitc.server.pojo.Role;
import com.example.demo.zjitc.server.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class IRoleService implements RoleService {
    @Autowired(required = false)
    private PermissionMapper permissionMapper;
    @Autowired(required = false)
    private RoleMapper roleMapper;
    public void add(Role role) {
        role.setPs_ids("0");
        roleMapper.insert(role);

    }

    public Role find(int id) {
        Role role = roleMapper.selectById(id);
        return role;
    }

    public void up(int id, Role role) {
        role.setRoleId(id);
        roleMapper.updateById(role);
    }

    public void del(int id) {
        roleMapper.deleteById(id);
    }

    public void uprole(int id, String rids) {
        Role role=new Role();
        role.setRoleId(id);
        role.setPs_ids(rids);
        roleMapper.updateById(role);
    }

    public List<Role> get() {
        List<Role> roleList = roleMapper.selectList(null);
        for (Role role: roleList) {
            String[] strs = role.getPs_ids().split(",");
            List<Permission> permissionList1=new ArrayList<>();
            List<Permission> permissionList2=new ArrayList<>();
            List<Permission> permissionList3=new ArrayList<>();
            for (int i = 0; i < strs.length; i++) {
                Permission permission = (Permission) permissionMapper.selectById(strs[i]);


                if(permission==null){
                    continue;
                }

                if(permission.getLevel().equals("0")){
                    permissionList1.add(permission);
                }
                if(permission.getLevel().equals("1")){
                    permissionList2.add(permission);
                }
                if(permission.getLevel().equals("2")){
                    permissionList3.add(permission);
                }


            }
            System.out.println(permissionList2);
            node(permissionList2,permissionList3);

            node(permissionList1,permissionList2);
            role.setChildren(permissionList1);


        }
        System.out.println(roleList);
        return roleList;
    }

    private void node(List<Permission> permissionList2, List<Permission> permissionList3) {
        for (Permission p1: permissionList2) {
            List<Permission> permissionList=new ArrayList<>();
            for (Permission p2:permissionList3) {
                if(p2.getPid()==p1.getId()){
                    permissionList.add(p2);
                }

            }
            p1.setChild(permissionList);
        }


    }
}
